//
//  WKPlayerViewController.m
//  WeKeTang
//
//  Created by ichina on 2017/9/14.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKPlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <ZFDownload/ZFDownloadManager.h>
#import "AppDelegate.h"
#import <ZFPlayerView.h>
#import "WKFMDBTools.h"

@interface WKPlayerViewController ()<ZFPlayerDelegate>

@property (strong, nonatomic) ZFPlayerView *playerView;

@property (nonatomic, strong) ZFPlayerModel *playerModel;

@property (nonatomic, strong) WKFMDBTools *dbManger;
/** 离开页面时候是否在播放 */
@property (nonatomic, assign) BOOL isPlaying;

@end

@implementation WKPlayerViewController

- (void)dealloc {
    NSLog(@"%@释放了",self.class);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // pop回来时候是否自动播放
    [self.playerView autoPlayTheVideo];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.playerView.playerPushedOrPresented = NO;
    self.playerView.delegate = nil;
    [self.playerView removeFromSuperview];
    self.playerView = nil;
    // push出下一级页面时候暂停
//     NSLog(@"-------------------%ld",self.navigationController.viewControllers.count);
    if ((self.navigationController.viewControllers.count == 3 && self.playerView && !self.playerView.isPauseByUser)||(self.navigationController.viewControllers.count == 4 && self.playerView && !self.playerView.isPauseByUser)||(self.navigationController.viewControllers.count == 2 && self.playerView && !self.playerView.isPauseByUser)||(self.navigationController.viewControllers.count == 6 && self.playerView && !self.playerView.isPauseByUser)||(self.navigationController.viewControllers.count == 5 && self.playerView && !self.playerView.isPauseByUser)){
//        self.isPlaying = YES;
        //        [self.playerView pause];
        
        [self.playerView removeFromSuperview];
        self.playerView = nil;
    }
   
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //self.zf_prefersNavigationBarHidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    self.dbManger = [WKFMDBTools defaultFMDBToos];
    
    NSString *seekTimeStr = [self.dbManger QueryWatchSeekTimeWithTableName:kDBWatchTableName section_videoid:self.section_videoid];
    NSLog(@"正在观看: %@",seekTimeStr);
    self.playerModel.seekTime = [seekTimeStr integerValue];
    
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(backGroundAction:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(foregroundAction:) name:UIApplicationWillEnterForegroundNotification object:nil];
}
#pragma mark - 程序进入后台
- (void)backGroundAction:(NSNotification*)nofi{
    
    [self.playerView pause];
}
#pragma mark - 程序进入前台
- (void)foregroundAction:(NSNotification*)nofi{
    __weak typeof(self) weakSelf = self;
    [self interfaceOrientation:UIInterfaceOrientationPortraitUpsideDown];
    self.playerView.frame = CGRectMake(0, 0, kDeviceScreenHeight, kDeviceScreenWidth);
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf interfaceOrientation:UIInterfaceOrientationLandscapeRight];
    });
    
    
    [self.playerView play];
}
- (BOOL)prefersStatusBarHidden {
    return ZFPlayerShared.isStatusBarHidden;
}
- (void)setupUI{
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
    [self interfaceOrientation:UIInterfaceOrientationLandscapeRight];
    
    
}
// 横屏 home键在右边
-(void)forceOrientationLandscapeWith:(UIViewController *)VC{
    
    AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.allowRotation=YES;
    [appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:VC.view.window];
    
    //强制翻转屏幕，Home键在右边。
    [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}
// 强制旋转
- (void)interfaceOrientation:(UIInterfaceOrientation)orientation{
    // arc下
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector             = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val                  = orientation;
        // 从2开始是因为0 1 两个参数已经被selector和target占用
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}
//支持旋转
-(BOOL)shouldAutorotate{
    return  !ZFPlayerShared.isLockScreen;;
}
// 支持哪些转屏方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

// 页面展示的时候默认屏幕方向（当前ViewController必须是通过模态ViewController（模态带导航的无效）方式展现出来的，才会调用这个方法）
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
#pragma mark - ZFPlayerDelegate
- (void)zf_playerFulleScreenAction{

    [self interfaceOrientation:UIInterfaceOrientationPortraitUpsideDown];
}
- (void)zf_playerBackAction {
    //总时长
    NSInteger totalTime = (NSInteger)(self.playerView.playerItem.duration.value / self.playerView.playerItem.duration.timescale);
    //当前时长
    NSInteger currentTime = CMTimeGetSeconds([self.playerView.playerItem currentTime]);
    NSLog(@"----%ld-----%ld",(long)currentTime,(long)totalTime);
    if (self.block) {
        
        self.block(currentTime, totalTime);
    }
    
    NSLog(@"-------------------%ld",self.navigationController.viewControllers.count);
    if (self.navigationController.viewControllers.count == 3 ||self.navigationController.viewControllers.count == 4||self.navigationController.viewControllers.count == 2) {
        self.playerView.playerPushedOrPresented = NO;
        if (self.backBlock) {
            self.backBlock();
        }
//        self.playerView.playerPushedOrPresented = NO;
         [self.navigationController popViewControllerAnimated:NO];
    }
    if (self.navigationController.viewControllers.count == 6||self.navigationController.viewControllers.count ==5) {
        self.playerView.playerPushedOrPresented = NO;
        if (self.backBlock) {
            self.backBlock();
        }
         [self.navigationController popViewControllerAnimated:NO];
    }
   //[self.navigationController popViewControllerAnimated:NO];
}
- (void)zf_playerDownload:(NSString *)url {
    NSLog(@"视频下载地址：%@",url);
//     此处是截取的下载地址，可以自己根据服务器的视频名称来赋值
    NSString *name = [url lastPathComponent];
    [[ZFDownloadManager sharedDownloadManager] downFileUrl:url filename:name fileimage:nil];
//     设置最多同时下载个数（默认是3）
    [ZFDownloadManager sharedDownloadManager].maxCount = 10;
}

- (void)zf_playerControlViewWillShow:(UIView *)controlView isFullscreen:(BOOL)fullscreen {
    //    self.backBtn.hidden = YES;
    [UIView animateWithDuration:0.25 animations:^{
//        self.backBtn.alpha = 0;
    }];
}

//- (void)zf_playerControlViewWillHidden:(UIView *)controlView isFullscreen:(BOOL)fullscreen {
//    //    self.backBtn.hidden = fullscreen;
//    [UIView animateWithDuration:0.25 animations:^{
////        self.backBtn.alpha = !fullscreen;
//    }];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];

}
- (ZFPlayerModel *)playerModel {
    if (!_playerModel) {
        _playerModel                  = [[ZFPlayerModel alloc] init];
        _playerModel.title            = self.section_name;
        _playerModel.videoURL         = [NSURL URLWithString:self.vurl];
       // NSURL *url                    = [NSURL URLWithString:self.placeholderImage];
       // NSData *data                  = [NSData dataWithContentsOfURL:url];
       // UIImage *image                = [UIImage imageWithData:data];
        //_playerModel.placeholderImage = image;
        _playerModel.fatherView       = self.view;
    }
    return _playerModel;
}

- (ZFPlayerView *)playerView {
    
    if (!_playerView) {
//        ZFPlayerControlView *controlView = [[ZFPlayerControlView alloc]init];
        _playerView = [[ZFPlayerView alloc] init];
        [_playerView playerControlView:nil playerModel:self.playerModel];
        // 设置代理
        _playerView.delegate = self;
        // 打开预览图
        _playerView.hasPreviewView = YES;
        _playerView.hasDownload = NO;
        
    }
    return _playerView;
}
@end
